package com.badibadi.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.FinalBitmap;

import org.json.JSONException;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.badibadi.activity.ActivityReadingActivity;
import com.badibadi.activity.AfterLandingActivity;
import com.badibadi.activity.ClubHomepageActivity;
import com.badibadi.activity.MyDataActivity;
import com.badibadi.activity.SeeOtherPeopleSpaceActivity;
import com.badibadi.fragment.AfterLandingMessageItem00.XListView1Adapter____1;
import com.badibadi.infos.Invite_Friend_Model;
import com.badibadi.infos.Pre_message_total;
import com.badibadi.infos.Results;
import com.badibadi.mytools.CalendarTools;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.DisplayUtil;
import com.badibadi.mytools.HtmlUtils;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.libjph.util.StringUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.view.my_view.XListView;
import com.view.my_view.XListView.IXListViewListener;

/**
 * //* 第二个fragment 创立 //*chuangli //* //
 **/
public class AfterLandingMessageItem01 extends BaseAppFragment implements
		IXListViewListener {
	// TODO Auto-generated method stub
	private String TAG = "AfterLandingMessageItem00";
	private XListView1Adapter____1 x1Adapter;
	private XListView xListView1;
	private int Page;
	private Results results, results2;
	private List<Pre_message_total> mList;// 数据

	List<Pre_message_total> list;
	// FinalBitmap finalBitmap;
	private DisplayImageOptions options;
	private int pageNum = 6;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(getActivity());
				
				try {
					onLoad();
					Utils.showMessage(getActivity(), getResources().getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
					// throw new NullPointerException("getActivity() is Null");
				}

				break;
			case 2:
				Utils.ExitPrgress(getActivity());
				try {
					xListView1.requestLayout();
					mList.addAll(list);
					x1Adapter.notifyDataSetChanged();
					onLoad();
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 3:
				Utils.ExitPrgress(getActivity());
				onLoad();
				try {
					Utils.showMessage(getActivity(), getResources().getString(R.string.l_xa10));
				} catch (Exception e) {
					// TODO: handle exception
					// throw new NullPointerException("getActivity() is Null");
				}
				break;
			case 4:
				Utils.ExitPrgress(getActivity());
				try {
					Utils.showMessage(getActivity(), results2.getRetmsg());
				} catch (Exception e) {
					// TODO: handle exception
					// throw new NullPointerException("getActivity() is Null");
				}
			default:
				break;
			}
		}
	};
	private String uid = "1";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mList = new ArrayList<Pre_message_total>();
		x1Adapter = new XListView1Adapter____1();
		// finalBitmap=FinalBitmap.create(getActivity());
		uid = getArguments().getString("uid");
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.ic_stub)
				.showImageForEmptyUri(R.drawable.noimage)
				.showImageOnFail(R.drawable.noimage).cacheInMemory()
				.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5)).build();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.xlistview, null);
		InitMyXListView1(view);
		return view;
	}

	public void InitMyXListView1(View view) {
		Page = 0;
		Constants.Invite_handler = mHandler;
		xListView1 = (XListView) view.findViewById(R.id.my_xListView1);
		xListView1.setXListViewListener(this);
		xListView1.setPullLoadEnable(true);
		xListView1.setPullRefreshEnable(true);
		xListView1.setAdapter(x1Adapter);
		xListView1.startLoadMore();
	}

	private void LoadingMessage(final int page) {
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				String lang = com.badibadi.mytools.Dialog
						.getSystemLanguageTypegrzx(getActivity());
				list = new ArrayList<Pre_message_total>();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", uid);
				map.put("type", "message_chuangli");
				map.put("page", page);
				map.put("lang", lang);
				map.put("pageNum", pageNum);
				String invite_content = Utils.sendRequest(map,
						Constants.BadiUrl + "message_total");
				//    
				if (invite_content != null) {
					results = Utils.checkResult_NNN(getActivity(),
							invite_content);
					if (results != null && !results.getRetmsg().equals("null")) {
//						   
						try {
							list = JSONUtils.getListByJsonString(
									results.getRetmsg(),
									Pre_message_total.class);

							mHandler.sendEmptyMessage(2);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							   
							mHandler.sendEmptyMessage(3);
						}
					} else {
						if (page > 1) {
							--Page;
						} else {
							Page = 1;
						}
						mHandler.sendEmptyMessage(3);
					}
				} else {
					if (page > 1) {
						--Page;
					} else {
						Page = 1;
					}
					mHandler.sendEmptyMessage(1);
				}

			}
		});
	}

	protected void onLoad() {
		xListView1.stopRefresh();
		xListView1.stopLoadMore();
		xListView1.setRefreshTime(""+getResources().getString(R.string.ganggang));
	}

	class XListView1Adapter____1 extends BaseAdapter {
		// private DisplayImageOptions options;

		public XListView1Adapter____1() {
			options = new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.ic_stub)
					.showImageForEmptyUri(R.drawable.noimage)
					.showImageOnFail(R.drawable.noimage).cacheInMemory()
					.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5))
					.build();
		}

		@Override
		public int getItemViewType(int position) {
			// TODO Auto-generated method stub
			if(!StringUtil.isNullOrEmpty(mList.get(position).getAid()))
				return 1;
			else
				return 0;
		}
		@Override
		public int getViewTypeCount() {
			// TODO Auto-generated method stub
			return 3;
		}
		
		@Override
		public int getCount() {

			return mList.size();
		}

		@Override
		public Object getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			int imageWH = 55;
			LayoutInflater mInflater = LayoutInflater.from(getActivity());

			ViewHolder holder = null;
			int type=getItemViewType(position);
			if (convertView == null) {
				if(type==0)
				{
					convertView = mInflater.inflate(R.layout.chuangli, parent,
							false);
					holder = new ViewHolder();
					// holder.text = (TextView) convertView.findViewById(R.id.text);
					// holder.icon = (ImageView)
					// convertView.findViewById(R.id.icon);
					holder.nickName = (TextView) convertView
							.findViewById(R.id.nickName);
					holder.name = (TextView) convertView.findViewById(R.id.name);
					holder.typeName = (TextView) convertView
							.findViewById(R.id.typeName);
					holder.motto = (TextView) convertView.findViewById(R.id.motto);
					holder.head = (ImageView) convertView.findViewById(R.id.head);
					holder.time = (TextView) convertView.findViewById(R.id.time);
				}else
				{
					convertView = mInflater.inflate(R.layout.chuangli_activity, parent,
							false);
					holder = new ViewHolder();
					holder.nickName = (TextView) convertView
							.findViewById(R.id.nickName);
					holder.head = (ImageView) convertView.findViewById(R.id.head);
					holder.time = (TextView) convertView.findViewById(R.id.time);
					holder.firends=(TextView)convertView.findViewById(R.id.frends);
					holder.name=(TextView)convertView.findViewById(R.id.name);
//					holder.typeName=(TextView)convertView.findViewById(R.id.typeName);
					holder.activityName=(TextView)convertView.findViewById(R.id.activityName);
				}
			
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
		
			// holder.text.setText(DATA[position]);
			// holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 :
			// mIcon2);
			// 昵称
			if(type==0)
			{
				showType0(position,convertView,
						holder);
			}else
			{
				showType1(position,convertView,
						holder);
			}
		

			return convertView;
		}
	}

	static class ViewHolder {
		public ImageView head;// 用户的头像
		public TextView nickName;// 用户的昵称
		public String uid;// 用户id
		public TextView firends;// 共同的好友
		public TextView motto;// 用户个性说明
		public String cid;// 俱乐部的id
		public TextView name;// 俱乐部的名字
		public TextView typeName;// 俱乐部的类型
		public TextView time;// 操作时间
		public String is_show;// 是否查看过 0：未查看，1：已查看
		public TextView activityName;//活动名称
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		Page = 1;
		mList = new ArrayList<Pre_message_total>();
		LoadingMessage(Page);
	}
	/**
	 * 如果创立的是活动
	 * @param position
	 * @param convertView
	 * @param holder
	 */
    public void showType1(final int position, View convertView, ViewHolder holder) {
		// TODO Auto-generated method stub
    	holder.nickName.setText("" + mList.get(position).getNickName());
		holder.nickName.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!StringUtil.isNullOrEmpty(mList.get(position).getId())) {
					if (mList.get(position).getId()
							.equals(Utils.getUid(getActivity()))) {
						Intent intent = new Intent(getActivity(),
								MyDataActivity.class);
						startActivity(intent);
					} else {
						Intent intent = new Intent(getActivity(),
								SeeOtherPeopleSpaceActivity.class);
						intent.putExtra("friend_id", mList.get(position)
								.getId());
						startActivity(intent);
					}
				}
			}
		});
		// 俱乐部名称
		holder.name.setText("" + mList.get(position).getClubName());
		holder.name.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!StringUtil.isNullOrEmpty(mList.get(position).getCid())) {
					Intent intent = new Intent(getActivity(),
							ClubHomepageActivity.class);
					intent.putExtra("cid", mList.get(position).getCid());
					startActivity(intent);
				}
			}
		});
		if(!StringUtil.isNullOrEmpty(mList.get(position).getHead()))
		{
			try {
				ImageLoader.getInstance().displayImage(
						Constants.BadiDownImgUrl + "/"
								+ mList.get(position).getHead()
								+ Constants.appPhoto4img, holder.head, options);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}else
		{
			Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.noimage);
			holder.head.setImageBitmap(bmp);
		}
		holder.head.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!StringUtil.isNullOrEmpty(mList.get(position).getId())) {
					if (mList.get(position).getId()
							.equals(Utils.getUid(getActivity()))) {
						Intent intent = new Intent(getActivity(),
								MyDataActivity.class);
						startActivity(intent);
					} else {
						Intent intent = new Intent(getActivity(),
								SeeOtherPeopleSpaceActivity.class);
						intent.putExtra("friend_id", mList.get(position)
								.getId());
						startActivity(intent);
					}
				}
			}
		});
		// 活动种类名称
//		holder.typeName.setText("" + mList.get(position).getActivityTypeName());
	    holder.firends.setText(""+mList.get(position).getFrends());//共同好友个数
	    try {
			holder.time.setText(""
					+ CalendarTools.getTimeChangeToString(getActivity(),mList.get(
							position).getTime()));
		} catch (Exception e) {
			// TODO: handle exception
		}
	    holder.activityName.setText(""+mList.get(position).getActivityName());//活动名称
	    holder.activityName.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(mList.get(position).getAid()!=null)
				{
					Intent intent=new Intent(getActivity(),ActivityReadingActivity.class);
					intent.putExtra("actId", mList.get(position).getAid());
					startActivity(intent);
				}
			}
		});
	    
    }

	/**
     * 第0种类 如果创立的是俱乐部
     * @param position
     * @param convertView
     * @param holder
     */
	public void showType0(final int position, View convertView, ViewHolder holder) {
		// TODO Auto-generated method stub
		holder.nickName.setText("" + mList.get(position).getNickName());
		holder.nickName.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!StringUtil.isNullOrEmpty(mList.get(position).getId())) {
					if (mList.get(position).getId()
							.equals(Utils.getUid(getActivity()))) {
						Intent intent = new Intent(getActivity(),
								MyDataActivity.class);
						startActivity(intent);
					} else {
						Intent intent = new Intent(getActivity(),
								SeeOtherPeopleSpaceActivity.class);
						intent.putExtra("friend_id", mList.get(position)
								.getId());
						startActivity(intent);
					}
				}
			}
		});
		// 俱乐部名称
		holder.name.setText("" + mList.get(position).getName());
		holder.name.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!StringUtil.isNullOrEmpty(mList.get(position).getCid())) {
					Intent intent = new Intent(getActivity(),
							ClubHomepageActivity.class);
					intent.putExtra("cid", mList.get(position).getCid());
					startActivity(intent);
				}
			}
		});
		// 座右铭
		// holder.motto.setEllipsize(TruncateAt.END);
		// holder.motto.setMaxEms(10);
		// holder.motto.setSingleLine(false);
		// holder.motto.setMaxLines(3);
		if (mList.get(position).getMotto() != null) {
			holder.motto.setText("" + mList.get(position).getMotto());
		} else {
			holder.motto.setText("");
		}

		// new HtmlUtils(getActivity(), holder.motto,
		// ""+mList.get(position).getMotto()).showTextView();
		// //头像
		// finalBitmap.display(holder.head,
		// Constants.BadiDownImgUrl+"/"+mList.get(position).getHead(),DisplayUtil.dip2px(getActivity(),
		// imageWH),DisplayUtil.dip2px(getActivity(), imageWH));
		if(!StringUtil.isNullOrEmpty(mList.get(position).getHead()))
		{
			try {
				ImageLoader.getInstance().displayImage(
						Constants.BadiDownImgUrl + "/"
								+ mList.get(position).getHead()
								+ Constants.appPhoto4img, holder.head, options);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}else
		{
			Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.noimage);
			holder.head.setImageBitmap(bmp);
		}
	

		holder.head.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!StringUtil.isNullOrEmpty(mList.get(position).getId())) {
					if (mList.get(position).getId()
							.equals(Utils.getUid(getActivity()))) {
						Intent intent = new Intent(getActivity(),
								MyDataActivity.class);
						startActivity(intent);
					} else {
						Intent intent = new Intent(getActivity(),
								SeeOtherPeopleSpaceActivity.class);
						intent.putExtra("friend_id", mList.get(position)
								.getId());
						startActivity(intent);
					}
				}
			}
		});
		// 俱乐部名称
		holder.typeName.setText("" + mList.get(position).getTypeName());
		// 发布时间
		try {
			holder.time.setText(""
					+ CalendarTools.getTimeChangeToString(getActivity(),mList.get(
							position).getTime()));
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		LoadingMessage(++Page);
	}
}